#!/bin/sh

# Loading configuration
if [ -f ${CASPER_CONF_DIR}/casperd.conf ]; then
	source ${CASPER_CONF_DIR}/casperd.conf
elif [ -f etc/casperd.conf ]; then
	source etc/casperd.conf
fi

export JOB_NAME=${1%%.*}
export JOB_ID=$2

export NODES_NUMBER=0
for i in ${NODES_USE}
do
        NODES_NUMBER=$((${NODES_NUMBER}+1))
done

# Controllo che esista la directory di lavoro di casper
if [ ! -d $CASPER_WORK_DIR ]; then
	mkdir $CASPER_WORK_DIR
fi

# Controllo che il file esista nel pool
if [ ! -f ${CASPER_POOL_DIR}/$1 ]; then
	echo jobs ${JOB_ID} error file $1 not found
	exit 1
fi

# Creo o svuoto la directory di lavoro del job
if [ ! -d ${CASPER_WORK_DIR}/${JOB_ID} ]; then
	mkdir ${CASPER_WORK_DIR}/${JOB_ID}
else
	rm -Rf ${CASPER_WORK_DIR}/${JOB_ID}/*
fi
mkdir ${CASPER_WORK_DIR}/${JOB_ID}/log

env | grep CASPER | awk '{ print "export " $0; }' > ${CASPER_WORK_DIR}/${JOB_ID}/variables
echo "export JOB_ID=${JOB_ID}" >> ${CASPER_WORK_DIR}/${JOB_ID}/variables
echo "export JOB_NAME=${JOB_NAME}" >> ${CASPER_WORK_DIR}/${JOB_ID}/variables
echo "export NODES_USE=\"${NODES_USE}\"" >> ${CASPER_WORK_DIR}/${JOB_ID}/variables
echo "export NODES_NUMBER=${NODES_NUMBER}" >> ${CASPER_WORK_DIR}/${JOB_ID}/variables

CMD=`echo $1 | awk -v file=${CASPER_POOL_DIR}/$1 -v work_dir=${CASPER_WORK_DIR}/${JOB_ID}/ -F . '{
	if ($NF == "zip") {
		print "unzip " file " -d " work_dir;
	}
	else if ($NF == "gz") {
		c = NF - 1;
		if ($c != "tar")
			exit;
		print "tar -zxf " file " -C " work_dir;
	}
	else if ($NF == "bz2") {
		c = NF - 1;
		if ($c != "tar")
			exit;
		print "tar -jxf " file " -C " work_dir;
	}
	else if ($NF == "tgz") {
		print "tar -zxf " file " -C " work_dir;
	}
	else if ($NF == "tbz" || $NF == "tbz2") {
		print "tar -jxf " file " -C " work_dir;
	}
}'`

if [ -z "${CMD}" ]; then
	echo "jobs ${JOB_ID} error file format not recognized"
	exit 1
fi

echo "jobs ${JOB_ID} status waiting"

${CASPER_ROOT_DIR}/scripts/casper-run.sh -l "extract" -m "extracting" -c "$CMD" --log "${CASPER_WORK_DIR}/${JOB_ID}/log/extraction.log"
if [ $? -ne 0 ]; then
	echo "ERROR: casper-launch-job.sh: extraction failed for job id ${JOB_ID}" >&2
	exit 1
fi

# Renaming files with spaces in names
find ${CASPER_WORK_DIR}/${JOB_ID}/ | while read fname
do
	if [ ! -f "$fname" ]; then
		continue
	fi
	NewName=`echo $fname | sed -e 'y/ /_/'`
	if [ "$fname" != "$NewName" ]; then
		mv "$fname" "$NewName"
	fi
done

echo "jobs ${JOB_ID} status extracted"

EXIT_STATUS=1

for plugin in `ls ${CASPER_PLUGINS_DIR}`
do
	if [ ! -d ${CASPER_PLUGINS_DIR}/${plugin} ]; then
		continue
	fi
	if [ ! -x ${CASPER_PLUGINS_DIR}/${plugin}/execute.sh ]; then
		continue;
	fi
	cd ${CASPER_PLUGINS_DIR}/${plugin}
	./execute.sh ${CASPER_WORK_DIR}/${JOB_ID} &
	echo "jobs ${JOB_ID} process $!"
	wait $!
	EXIT_STATUS=$?
	echo "jobs ${JOB_ID} process-term $!"
	if [ $EXIT_STATUS -eq 0 ]; then
		break
	fi
done

exit $EXIT_STATUS
